//引入http
const http = require("http");
//引入express
const express = require("express");
//引入multer
const multer = require("multer");
const fs = require("fs");
const mongoose = require("mongoose");
var Photo = require('../models/Photo');
var PhotoType = require('../models/PhotoType');
mongoose.connect("mongodb://localhost:27017/upload", {
    useNewUrlParser: true
});
mongoose.Promise = Promise;

/*var server=http.createServer(app);*/
var router = express.Router();

var createFolder = function(folder) {
    try {
        fs.accessSync("./public/" + folder);
    } catch (e) {
        fs.mkdirSync("./public/" + folder);
    }
};
var uploadFolder = './public/upload/';
createFolder("./upload/");
// 通过 filename 属性定制
var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, uploadFolder); // 保存的路径，备注：需要自己创建
    },
    filename: function(req, file, cb) {
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        cb(null, file.originalname);
    }
});

router.get('/', function(req, res) {
    res.render('index')
});

router.post('/init', function (req, res) {
    const { typeId, size, page } = req.body;
    console.log("typeid " + typeId + " " + size + " " + page);

    // res.send(typeId)
    queryData(typeId, size, page, res);
    // console.log(typeId, size);

});

router.post('/initType', function (req, res) {
    queryType(res);
});


router.post('/deletePhoto', function (req, res) {
    const {photoId, typeId} = req.body;
    Photo.remove({ "photoId": photoId, "typeId": typeId}, function(err, result) {
        if (err) {
            return;
        }
        console.log("ggggggggg " + result);
        res.send({"result": result});
    })
});

router.post('/sort', function (req, res) {
    const { typeId, typeName } = req.body;
    saveType(new PhotoType({
        "typeId": typeId,
        "typeName": typeName
    }), req, res);
});

router.post('/count', function(req, res) {
    getAllCount(req.body.typeId, res);
});

// 通过 storage 选项来对 上传行为 进行定制化
var upload = multer({ storage: storage })
    // 单图上传
router.post('/upload', upload.single('file'), function(req, res, next) {
    const { photoId, typeId } = req.body;
    console.log(photoId);
    savePhoto(new Photo({
        "photoId": photoId,
        "photoName": req.file.filename,
        "photoSrc": "../public/javascripts/" + req.file.filename,
        "typeId": typeId
    }), req, res);
});

function getAllCount(typeId, res) {
    console.log(typeId);
    Photo.count({ "typeId": typeId}, function(error, count) {
        console.log("count " + count);
        res.send({ "count": count});
    })
}

async function queryType(res) {
    let type = await PhotoType.find();
    res.send(type);
}

async function queryData(typeId, size, page, res) {
    page = parseInt(page) || 1;
    console.log((page - 1) * parseInt(size));
    
    const photo = Photo.find();
    const result = await photo.where("typeId").eq(typeId)
        .limit(parseInt(size))
        .skip((page - 1) * parseInt(size));
    // console.log(result);
    res.send(result)
}

async function savePhoto(data, req, res) {
    let result = '';
    // await User.remove();
    // const list = await User.find();
    // console.log();
    const all = await Photo.find();
    console.log(all.length);
    const list = await Photo.find({ 'photoId': data.photoId });
    if (Array.isArray(list) && list.length === 0) {
        await data.save();
        result = '上传成功!';
        console.log(result);
        res.send({ "str": result, "file": req.file });
    } else if (Array.isArray(list) && list.length > 0) {
        result = '图片已存在!';
        console.log(result);
        res.send({ "str": result, "file": req.file });
    }
}


async function saveType(data, req, res) {
    let result = '';
    // await User.remove();
    // const list = await User.find();
    // console.log();
    // await PhotoType.remove();
    const all = await PhotoType.find();
    console.log(all.length);
    const list = await PhotoType.find({ 'typeId': data.typeId });
    if (Array.isArray(list) && list.length === 0) {
        await data.save();
        result = '上传成功!';
        console.log(result);
        res.send({ "str": result, "file": req.file });
    } else if (Array.isArray(list) && list.length > 0) {
        result = '类型已存在!';
        console.log(result);
        res.send({ "str": result, "file": req.file });
    }
}













//处理来自页面的ajax请求。single文件上传
router.post('/uploads', upload.single('file'), function(req, res, next) {
    //拼接文件上传后的网络路径
    console.log("file:" + req.file.originalname)
    var url = 'http://' + req.headers.host + '/upload/' + req.file.originalname;

    res.end(req.file.originalname);
});

// 单域多文件上传：input[file]的 multiple=="multiple"
router.post('/upload', upload.array('file', 5), function(req, res, next) {
    // req.files 是 前端表单name=="imageFile" 的多个文件信息（数组）,限制数量5，应该打印看一下
    var fileName = ""
    for (var i = 0; i < req.files.length; i++) {
        // 图片会放在uploads目录并且没有后缀，需要自己转存，用到fs模块
        // 对临时文件转存，fs.rename(oldPath, newPath,callback);
        fileName += req.files[i].originalname + ";"
        fs.rename(req.files[i].path, "upload/" + req.files[i].originalname, function(err) {
            if (err) {
                throw err;
            }
            console.log('done!');
        })
    }


    res.writeHead(200, {
        "Access-Control-Allow-Origin": "*" //允许跨域。。。
    });
    // req.body 将具有文本域数据, 如果存在的话
    //  res.end(JSON.stringify(req.files)+JSON.stringify(req.body));
    console.log("fileName:" + fileName)
    res.end(fileName)
})


module.exports = router;